package com.one.common.view.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.one.common.R;
import com.one.common.manager.ActivityPageManager;
import com.one.common.manager.event.BusManager;
import com.one.common.presenter.BasePresenter;
import com.one.common.utils.LayoutUtils;
import com.one.common.utils.Logger;
import com.one.common.utils.Toaster;
import com.one.common.view.pagestate.page.PageInterFace;
import com.one.common.view.widget.MyTitleBar;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Author：zhulunjun
 * Time：2017/9/13
 * description：activity 基类
 */

public abstract class BaseActivity<T extends BasePresenter> extends RxAppCompatActivity implements PageInterFace,
        View.OnClickListener {
    public T mPresenter;
    public Context mContext;
    public BaseActivity myRxActivity;
    private boolean isHasTitleBar = true;
    private MyTitleBar myTitleBar = null;
    public String TAG;
    private Unbinder unbinder;
    public ProgressDialog loadingDialog; // 网络加载弹窗

    public Context getContext() {
        return mContext;
    }

    /**
     * 获取IPresenter
     * 如果没有初始化，则用父类的对象
     */
    protected BasePresenter getPresenter() {
        if (mPresenter == null) {
            return new BasePresenter();
        } else {
            return mPresenter;
        }
    }

    /**
     * 初始化presenters,由子类实现
     */
    protected abstract void initPresenter();

    /**
     * 在setContentView之前
     */
    @Override
    public void beforeCreateView() {
        initTitle();
    }

    @Override
    public int getSecondLayoutResId() {
        return -1;
    }


    /**
     * 在setContentView之前
     */


    @Override
    public void afterCreateView() {
        // 使用ButterKnife注入,先加载布局，后绑定ButterKnife。
        unbinder = ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        mContext = this;
        myRxActivity = this;
        TAG = myRxActivity.getClass().toString();
        ActivityPageManager.getAppManager().addActivity(this);

        initPresenter();
        getPresenter().onCreate();// 这里这么写是因为，如果有需要在onCreate生命周期中执行的业务，可以卸载对应的Presenter中
        initRxBus();
        setActivityAnimation(0);
        initView();
        setStatusBar();
        initLoading();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        initData();
    }

    public void initView(){

    }
    public void initData(){

    }
    @Override
    public boolean haveRootView() {
        return false;
    }
    /**
     * 初始化顶部设置
     */
    protected void initTitle() {
        myTitleBar = new MyTitleBar(this);
        myTitleBar.getmBack().setOnClickListener(this);
        myTitleBar.getmIvRight().setOnClickListener(this);
        myTitleBar.getmTvRight().setOnClickListener(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        beforeCreateView();
        // 初始化toolbar.和布局
        if(getLayoutResId() != -1 && !haveRootView()) {
            dependToSetContentView(getLayoutResId());
        } else {
            dependToSetContentView(getSecondLayoutResId());
        }
        afterCreateView();

    }

    /**
     * 设置布局，若有titleBar则设置默认监听
     */
    protected void dependToSetContentView(int resId) {
        int layoutResId = getLayoutResId();
        if (layoutResId > 0) {
            LinearLayout root = new LinearLayout(this);
            LayoutUtils.setViewGroupParams(root, LayoutUtils.MATCH, LayoutUtils.MATCH);
            root.setOrientation(LinearLayout.VERTICAL);

            if (isHasTitleBar) {
                root.addView(myTitleBar);
            }
            View content = View.inflate(this, resId, null);
            LayoutUtils.setLinearParams(content, LayoutUtils.MATCH, LayoutUtils.MATCH);
            root.addView(content);
            // 设置所有页面的通用背景色
            root.setBackgroundColor(getResources().getColor(R.color.white));

            setContentView(root);
        }
    }

    /**
     * 设置状态栏的颜色
     * 如果是有titlebar的，titlebar和状态栏同色
     * <p>
     * 只对5.0以上的系统做处理
     */
    public void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setStatusBarUpperAPI21();

//            if (isHasTitleBar) {
//                this.findViewById(R.id.my_title_bar).setBackgroundColor(color);
//            }

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            setStatusBarUpperAPI19();
        }


    }

    // 5.0版本以上
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void setStatusBarUpperAPI21() {
        Window window = getWindow();
        //设置透明状态栏,这样才能让 ContentView 向上
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(this.getResources().getColor(R.color.black));

        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 使其不为系统 View 预留空间.
            ViewCompat.setFitsSystemWindows(mChildView, false);
        }
    }

    // 4.4 - 5.0版本
    private void setStatusBarUpperAPI19() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        View statusBarView = mContentView.getChildAt(0);
        //移除假的 View
        if (statusBarView != null && statusBarView.getLayoutParams() != null &&
                statusBarView.getLayoutParams().height == getStatusBarHeight()) {
            mContentView.removeView(statusBarView);
        }
        //不预留空间
        if (mContentView.getChildAt(0) != null) {
            ViewCompat.setFitsSystemWindows(mContentView.getChildAt(0), false);
        }
    }

    private int getStatusBarHeight() {
        int result = 0;
        int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resId > 0) {
            result = getResources().getDimensionPixelSize(resId);
        }
        return result;
    }

    private void initRxBus() {
        BusManager.getBus().register(this);
    }

    /**
     * 初始化loading
     */
    private void initLoading() {
        if(loadingDialog == null) {
            loadingDialog = new ProgressDialog(this);
        }
    }

    @Override
    public void showLoading() {
        if(loadingDialog != null && !loadingDialog.isShowing()){
            loadingDialog.show();
        }
    }

    @Override
    public void cancelLoading() {
        if(loadingDialog != null && loadingDialog.isShowing()){
            loadingDialog.dismiss();
        }
    }

    /**
     * 获取标题栏
     */
    public MyTitleBar getMyTitleBar() {
        return myTitleBar;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_title_bar_back) {
            Logger.d("嘻嘻嘻嘻嘻嘻嘻嘻 iv_back");
            onClickBack();
        } else if (id == R.id.tv_title_bar_right) {
            onClickRightText(v);
        } else if (id == R.id.iv_title_bar_right) {
            onClickRightImg(v);
        }
    }


    /**
     * 没有titlebar时调用这个函数
     */
    public void noHasTitle() {
        isHasTitleBar = false;
    }

    /**
     * 点击返回按钮
     */
    protected void onClickBack() {
        onBackPressed();
    }

    /**
     * 点击右侧文字
     */

    protected void onClickRightText(View v) {
        onClickRightText();
    }

    protected void onClickRightText() {
    }

    /**
     * 点击右侧图片
     */
    protected void onClickRightImg(View v) {
        onClickRightImg();
    }

    protected void onClickRightImg() {
    }

    @Override
    protected void onStart() {
        super.onStart();
        getPresenter().onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getPresenter().onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        getPresenter().onPause();

    }

    @Override
    protected void onStop() {
        super.onStop();
        getPresenter().onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(unbinder != null) {
            unbinder.unbind();
        }
        getPresenter().onDestroy();// 目前BasePresenter.onDestroy() 写解绑方法
        //页面销毁时清除activity栈中的对象，防止内存泄漏
        ActivityPageManager.getAppManager().removeActivity(this);
        BusManager.getBus().unregister(this);
    }

    /**
     * toast默认的展示方法，如果有特殊要求，在子类中重写该方法
     */
    public void showToast(String msg) {
        Toaster.showShortToast(msg);
    }

    @Override
    public void finishPage() {
        finish();
    }

    @Override
    public void finish() {
        super.finish();
        setActivityAnimation(1);
    }

    /**
     * 设置activity转场动画
     */
    public void setActivityAnimation(int flag) {
        if (myTitleBar != null) {
            int va = myTitleBar.getmMode().getIntValue();
            if (va % 2 != 0) {
                if (flag == 0) {  //进入
                    overridePendingTransition(R.anim.slide_in_bottom, R.anim.anim_no);
                } else {     //退出
                    overridePendingTransition(R.anim.anim_no, R.anim.slide_out_bottom);
                }
                return;
            }
        }
        if (flag == 0) { //进入
            overridePendingTransition(R.anim.slide_in_right, R.anim.anim_no);
        } else {        //退出
            overridePendingTransition(R.anim.anim_no, R.anim.slide_out_right);
        }
    }


}
